<template>
  <div class="downloads-page">
    <el-row :gutter="20" class="file-grid">
      <el-col 
        v-for="file in fileList" 
        :key="file.id" 
        :xs="24" 
        :sm="12" 
        :md="8" 
        :lg="6">
        <el-card class="file-card" shadow="hover">
          <div class="file-icon">
            <el-icon size="40">
              <Document v-if="isDocument(file.fileType)" />
              <Picture v-else-if="isImage(file.fileType)" />
              <VideoCamera v-else-if="isVideo(file.fileType)" />
              <Folder v-else />
            </el-icon>
          </div>
          <h3 class="file-name">{{ file.fileName }}</h3>
          <div class="file-info">
            <span>大小：{{ formatFileSize(file.fileSize) }}</span>
            <span>下载次数：{{ file.downloadCount }}</span>
          </div>
          <div class="file-actions">
            <el-button 
              type="primary" 
              @click="handleDownload(file)">
              下载文件
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Document, Picture, VideoCamera, Folder } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { API_BASE_URL } from '@/config'

const baseUrl = API_BASE_URL
const fileList = ref([])

// 获取可下载的文件列表
const getFileList = async () => {
  try {
    const res = await fetch(`${baseUrl}/api/file/list`)
    const data = await res.json()
    if (data.code === 0) {
      fileList.value = data.data.filter(file => 
        file.status === 0 && file.residualDegree > 0
      )
    }
  } catch (error) {
    ElMessage.error('获取文件列表失败')
  }
}

// 下载文件
const handleDownload = (file) => {
  window.open(`${baseUrl}/api/file/download/${file.id}`)
}

// 文件类型判断
const isDocument = (type) => {
  return ['doc', 'docx', 'pdf', 'txt'].includes(type.toLowerCase())
}

const isImage = (type) => {
  return ['jpg', 'jpeg', 'png', 'gif'].includes(type.toLowerCase())
}

const isVideo = (type) => {
  return ['mp4', 'avi', 'mov'].includes(type.toLowerCase())
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

onMounted(() => {
  getFileList()
})
</script>

<style scoped>
.downloads-page {
  padding: 20px;
}

.file-grid {
  margin-bottom: 20px;
}

.file-card {
  margin-bottom: 20px;
  text-align: center;
}

.file-icon {
  margin: 20px 0;
  color: #409EFF;
}

.file-name {
  margin: 10px 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-info {
  display: flex;
  justify-content: space-around;
  color: #666;
  font-size: 14px;
  margin: 10px 0;
}

.file-actions {
  margin: 15px 0;
}
</style> 